package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;

import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;



    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest req) {
        log.info("手机号码为:{}", user.getPhone());
        String phone = user.getPhone();
        if (phone != null) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            /*SMSUtils.sendMessage("调用阿里云的服务器发验证消息");*/
            log.info("验证码:{}", code);
            //req.getSession().setAttribute(phone, code);
            //设置验证码存活时间为5分钟
            redisTemplate.boundValueOps(phone).set(code, 5, TimeUnit.MINUTES);


            return R.success("验证码发送成功!");
        }
        return R.error("验证码发送失败!");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpServletRequest req) {
        log.info("获取到的map集合{}", map.toString());
        //获取登录的手机号码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //从session中获取验证码
        //String correctCode = req.getSession().getAttribute(phone).toString();
        String correctCode = redisTemplate.boundValueOps(phone).get().toString();
        //进行验证码比对
        if (correctCode != null && correctCode.equals(code)) {
            //条件构造器
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone, phone);
            User user = userService.getOne(lqw);
            //判断用户是否注册
            if (user == null) {
                //新用户,自动注册添加到数据库
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //像session中存入用户id
            req.getSession().setAttribute("user", user.getId());
            //删除session中的code
            //req.getSession().removeAttribute(phone);
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登录失败");
    }
}
